package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.constant.WeChatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获取微信用户的openid
        String openid = weChatLogin(userLoginDTO.getCode());
        //判断微信是否成功登录
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //获取用户的基本信息
        User user=userMapper.getByOpenid(openid);
        //如果用户不存在则自动注册
        if(user == null){
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }


        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String weChatLogin(String code) {
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put(WeChatConstant.APPID_PARAM,weChatProperties.getAppid());
        paramMap.put(WeChatConstant.SECRET_PARAM,weChatProperties.getSecret());
        paramMap.put(WeChatConstant.JS_CODE_PARAM,code);
        paramMap.put(WeChatConstant.GRANT_TYPE_PARAM,WeChatConstant.GRANT_TYPE_PARAM_KEY);
        String response= HttpClientUtil.doGet(WeChatConstant.LOGIN_URL,paramMap);
        JSONObject jsonObject= JSONObject.parseObject(response);
        String openid=jsonObject.getString(WeChatConstant.OPENID_NAME);
        return openid;
    }
}
